import logging
from contextlib import contextmanager
from src.config.conf import cfg
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import QueuePool
from sqlalchemy import create_engine, exists, select, func
from src.service.models.website_shipping import WebsiteShipping
import datetime
from src.common.logger import get_logger
from loguru import logger

db_logger = get_logger("sqlalchemy.engine", logging.INFO)

SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://{cfg.mysql.username}:{cfg.mysql.password}@{cfg.mysql.host}:{cfg.mysql.port}/{cfg.mysql.database}?charset=utf8mb4"

engine = create_engine(
    SQLALCHEMY_DATABASE_URI,
    echo_pool=True,
    poolclass=QueuePool,
    pool_size=20,
    pool_timeout=30,
    pool_recycle=3600,  # 60分钟后主动回收连接
    hide_parameters=False,
    pool_pre_ping=True,  # 发送连接请求时提前ping，检测连接是否可用
)

SessionLocal = sessionmaker(autoflush=False, autocommit=False, bind=engine)

Base = declarative_base()


@contextmanager
def get_mysql():
    db = None
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()
